import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# 加载数据
input_file = 'F:/python学习资料/Python-Machine-Learning-Cookbook-master/Chapter04/data_multivar.txt'
# 加载数据
x = []
with open(input_file,'r') as f:
    for line in f.readlines():
        data = [float(i) for i in line.split(',')]
        x.append(data)

data = np.array(x)
num_clusters = 4
plt.figure()
plt.scatter(data[:,0],data[:,1],marker='o',facecolors='none',edgecolors='k',s=30)
x_min,x_max = min(data[:,0])-1,max(data[:,0])+1
y_min,y_max = min(data[:,1])-1,max(data[:,1])+1
plt.title("Input data")
plt.xlim(x_min,x_max)
plt.ylim(x_min,x_max)
plt.xticks(())
plt.yticks(())
plt.show()

# 训练模型
kmeans = KMeans(init='k-means++',n_clusters=num_clusters,n_init=10)
kmeans.fit(data)

# print(kmeans.cluster_centers_)
# print(kmeans.labels_[:5])
# 可视化边界
step_size = 0.01
# 画出边界
x_min,x_max =min(data[:,0])-1,max(data[:,0])+1
y_min,y_max = min(data[:,1])-1,max(data[:,1])+1
x_values,y_values = np.meshgrid(np.arange(x_min,x_max,step_size),
                                np.arange(y_min,y_max,step_size))
# 预测网格中所有数据点的标签
predicted_labels = kmeans.predict(np.c_[x_values.ravel(),y_values.ravel()])
# 画出结果
predicted_labels = predicted_labels.reshape(x_values.shape)
plt.figure()
plt.clf()
plt.imshow(predicted_labels,interpolation='nearest',cmap=plt.cm.Paired,
           extent=(x_values.min(),x_values.max(),y_values.min(),y_values.max()),
           aspect='auto',origin='center')
plt.scatter(data[:,0],data[:,1],marker='o',facecolors='none',edgecolors='k',s=60)
# 画出质心
centers = kmeans.cluster_centers_
plt.scatter(centers[:,0],centers[:,1],marker='o',s=200,color='k',facecolors='black')
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.show()